package com.xindaoapp.happypet.protocol;

import java.io.File;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Pair;

import com.lidroid.xutils.util.LogUtils;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MyPostActivity;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PostInfo3;
import com.xindaoapp.happypet.protocol.CustomMultipartEntity.ProgressListener;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.KeyValuePair;
import com.xindaoapp.happypet.utils.NotifyManager;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.utils.ThreadPool;
import com.xindaoapp.share.SharePopupWindow;


public class PostQueueImpl implements PostQueue {
    private final UploadPost iPost;
    public PostInfo3 mPostInfos = new PostInfo3();
    private final String mUid;

    private List<KeyValuePair<String, Integer>> infos;

    private KeyValuePair<String, Integer> sendingInfo;
    /** 发送过程，正在发送 */
    public boolean isPosting;
    private IUploadProgress iUploadProgress;

    private final Context mContext;

    private boolean isHaveVideo;

    private Activity activity;

    private final ProgressListener iProgressListener = new ProgressListener() {

        @Override
        public void transferred(final long num) {
            HappyPetApplication.mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (sendingInfo != null) {
                        int progress =
                                (int) (num * 1.0 / new File(sendingInfo.first).length() * 100);
                        iUploadProgress.progress(progress);
                    }
                }
            });
        }
    };
    private ProgressHUD mProgressHUD;


    public PostQueueImpl(Context context, String mUid, String fid, long postTime,
            IUploadProgress iUploadProgress) {
        super();
        this.mContext = context;
        mPostInfos.fid = fid;
        mPostInfos.postTime = postTime;
        this.mUid = mUid;
        iPost = new UploadPostImpl();
        this.iUploadProgress = iUploadProgress;
    }

    public PostQueueImpl(Context context, String mUid, long postTime, String tags,
            IUploadProgress iUploadProgress) {
        super();
        this.mContext = context;
        mPostInfos.tags = tags;
        mPostInfos.postTime = postTime;
        this.mUid = mUid;
        iPost = new UploadPostImpl();
        this.iUploadProgress = iUploadProgress;
    }

    public PostQueueImpl(Context context, String mUid, PostInfo3 info) {
        super();
        this.mContext = context;
        this.mUid = mUid;
        mPostInfos = info;
        iPost = new UploadPostImpl();
    }

    /**
     * 添加事件监听器
     * 
     * @param iUploadProgress
     */
    @Override
    public void addListener(IUploadProgress iUploadProgress) {
        this.iUploadProgress = iUploadProgress;
    }

    @Override
    public void start(IUploadProgress iUploadProgress) {
        this.iUploadProgress = iUploadProgress;
        post();
    }

    /**
     * 添加一个图片文件上传到队列
     * 
     * @param mSplashBannerInfo 图片文件
     */
    @Override
    public void addQueue(List<KeyValuePair<String, Integer>> infos) {
        mPostInfos.sendingArray.addAll(infos);
        if (!isPosting) {
            post();
        }
    }

    /**
     * 添加一个视频文件
     * 
     * @param info 视频文件信息
     * @param coverFilePath 封面地址
     */
    @Override
    public void addQueue(KeyValuePair<String, Integer> info, String coverFilePath) {
        mPostInfos.videoCover = coverFilePath;
        mPostInfos.sendingArray.add(info);
        if (!isPosting) {
            post();
        }
    }

    /**
     * 发帖
     * 
     * @param title
     * @param content
     */
    @Override
    public void addQueue(String title, String content, List<KeyValuePair<String, Integer>> infos,
            boolean isHaveVideo, String webVideoData, int isSendShare) {
        mPostInfos.title = title;
        mPostInfos.content = content;
        this.infos = infos;
        mPostInfos.webvideodata = webVideoData;
        mPostInfos.isSendShare = isSendShare;

        this.isHaveVideo = isHaveVideo;

        // notifySendingBody();

        mProgressHUD = ProgressHUD.show(mContext, "正在发送，请稍后...", true, true, null);
        mProgressHUD.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (activity != null) {
                    activity.finish();
                }
            }
        });
        if (!isPosting) {
            post();
        } else {
            notifyStart(0, 0, true);
        }
    }

    /**
     * 未点击发帖，直接保存到草稿箱
     * 
     * @param title
     * @param content
     */
    @Override
    public void addQueueToDraft(String title, String content,
            List<KeyValuePair<String, Integer>> infos, boolean isHaveVideo, String webVideoData,
            int isSendShare) {
        mPostInfos.title = title;
        mPostInfos.content = content;
        this.infos = infos;
        mPostInfos.webvideodata = webVideoData;
        mPostInfos.isSendShare = isSendShare;

        this.isHaveVideo = isHaveVideo;
    }

    /**
     * 发帖到草稿箱
     * 
     * @param title
     * @param content
     */
    @Override
    public void saveToDraft() {
        saveToDB();
    }

    /**
     * 回复
     * 
     * @param content
     * @param tid
     * @param pid
     * @param infos
     */
    @Override
    public void addQueue(String content, String tid, String pid,
            List<KeyValuePair<String, Integer>> infos, String webVideoData) {
        mPostInfos.content = content;
        mPostInfos.tid = tid;
        mPostInfos.pid = pid;
        this.infos = infos;
        mPostInfos.webvideodata = webVideoData;

        // notifySendingBody();

        if (!isPosting) {
            post();
        } else {
            notifyStart(0, 0, true);
        }
    }



    @Override
    public void finishActivity(Activity activity) {
        this.activity = activity;
    }

    public void addQueue(String title, String content, String tid, String pid,
            List<KeyValuePair<String, Integer>> infos) {
        mPostInfos.title = title;
        mPostInfos.content = content;
        mPostInfos.tid = tid;
        mPostInfos.pid = pid;
        this.infos = infos;
        if (!isPosting) {
            post();
        } else {
            notifyStart(0, 0, true);
        }
    }

    /**
     * 验证传输是否中断
     */
    private boolean isInterrupt(int i) {
        // 验证图片是否已经上传过
        for (KeyValuePair<String, String> value : mPostInfos.successArray.first) {
            if (value.first.equals(mPostInfos.sendingArray.get(i).first)) {
                return true;
            }
        }

        // 验证视频是否已经上传过
        for (KeyValuePair<String, String> value : mPostInfos.successArray.second) {
            if (value.first.equals(mPostInfos.sendingArray.get(i).first)) {
                return true;
            }
        }

        return false;
    }

    private void notifyStart(final int current, final int size, final boolean isNotify) {
        HappyPetApplication.mHandler.post(new Runnable() {

            @Override
            public void run() {
                iUploadProgress.start(current, size);
            }
        });
    }

    /**
     * 上传文件
     * 
     * @return true 上传成功
     */
    private boolean startPostFile(KeyValuePair<String, Integer> sendingInfo) {
        this.sendingInfo = sendingInfo;
        Pair<Boolean, String> pair = null;
        if (sendingInfo.second == 0) {// 上传图片
            // 图片进行压缩处理，压缩至100以下
            if (!new File(sendingInfo.first).exists() || new File(sendingInfo.first).length() == 0) {// 如果不错
                // mPostInfos.sendingArray.remove(sendingInfo);
                errorCount++;
                return false;
            }
            pair =
                    iPost.post(mUid, mPostInfos.fid, CommonUtil.compressImage(sendingInfo.first),
                            iProgressListener);
        } else if (sendingInfo.second == 1) {// 上传视频
            if (!new File(sendingInfo.first).exists() || !new File(mPostInfos.videoCover).exists()) {// 如果不错
                return false;
            }
            pair =
                    iPost.post(mUid, mPostInfos.fid, new File(sendingInfo.first),
                            CommonUtil.compressImage(mPostInfos.videoCover), iProgressListener);
        }
        if (pair.first) {
            if (sendingInfo.second == 0) { // 图片上传成功
                mPostInfos.successArray.first.add(new KeyValuePair<String, String>(
                        sendingInfo.first, pair.second));
            } else if (sendingInfo.second == 1) { // 视频上传成功
                mPostInfos.successArray.second.add(new KeyValuePair<String, String>(
                        sendingInfo.first, pair.second));
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取正在发送的信息
     */
    @Override
    public KeyValuePair<String, Integer> getSendingInfo() {
        return sendingInfo;
    }

    private int errorCount = 0;// 文件路径错误的个数

    /**
     * 发送文件
     * 
     * @return
     */
    private boolean postFiles() {
        // int size = mPostInfos.sendingArray.size();

        for (int i = 0; i < mPostInfos.sendingArray.size(); i++) {
            if (isInterrupt(i)) {
                continue;
            }

            notifyStart(i + 1, mPostInfos.sendingArray.size(), false);

            if (!startPostFile(mPostInfos.sendingArray.get(i))) {
                continue;
            };
        }

        if ((mPostInfos.sendingArray.size() - errorCount) == mPostInfos.successArray.first.size()) {
            return true;
        }
        return false;
    }

    /**
     * 整个发送过程<br/>
     * 1、上传文件<br/>
     * 2、上传正文
     */
    private void post() {
        ThreadPool.addRunnable(new Runnable() {

            @Override
            public void run() {
                isPosting = true;
                postFiles();
                postMainBody();
                isPosting = false;
            }
        });
    }


    private boolean isFileError = false;

    /**
     * 发布帖子正文
     */
    private void postMainBody() {
        // 判断是否上传正文
        if (!TextUtils.isEmpty(mPostInfos.title) || !TextUtils.isEmpty(mPostInfos.tid)) {

            int successSize =
                    mPostInfos.successArray.first.size() + mPostInfos.successArray.second.size();

            // 当前有正在发送的文件，并且发送成功的数量和发送的数量不一致
            if (mPostInfos.sendingArray.size() > 0
                    && successSize != (mPostInfos.sendingArray.size() - errorCount)) {
                if (errorCount > 0)
                    isFileError = true;
                errorCount = 0;// 文件路径错误的个数
                if (mProgressHUD != null) {
                    mProgressHUD.dismiss();
                }
                sendFailed();
                isPosting = false;
                return;
            }

            Pair<Boolean, String> pair = null;
            if (TextUtils.isEmpty(mPostInfos.tid)) {// 发帖
                pair =
                        iPost.post(mUid, mPostInfos.fid, mPostInfos.title, mPostInfos.content,
                                isHaveVideo ? "" : parseAidList(mPostInfos.successArray.first),
                                isHaveVideo ? parseAidList(mPostInfos.successArray.second) : "",
                                mPostInfos.webvideodata, mPostInfos.isSendShare, iProgressListener);
            } else {// 回复
                pair =
                        iPost.post(mUid, mPostInfos.fid, mPostInfos.title, mPostInfos.content,
                                parseAidList(mPostInfos.successArray.first),
                                parseAidList(mPostInfos.successArray.second), mPostInfos.tid,
                                mPostInfos.pid, mPostInfos.webvideodata, iProgressListener);
            }

            if (mProgressHUD != null) {
                mProgressHUD.dismiss();
            }
            isFileError = false;

            if (pair.first) {// 发帖成功
                if (activity != null)
                    activity.finish();
                sendSuccess(pair.second);
            } else {
                sendFailed(pair.second);
                isPosting = false;
                return;
            }
        }
    }

    /**
     * 发送正文提醒
     */
    private void notifySendingBody() {
        HappyPetApplication.mHandler.post(new Runnable() {

            @Override
            public void run() {
                iUploadProgress.start(0, 0);
                if (TextUtils.isEmpty(mPostInfos.tid)) {
                    NotifyManager.showUploadPostNotify(mContext,
                            mContext.getString(R.string.sending_post),
                            mContext.getString(R.string.sending_post), "", NotifyManager.sPOST,
                            new Intent());
                } else {
                    NotifyManager.showUploadPostNotify(mContext,
                            mContext.getString(R.string.sending_reply),
                            mContext.getString(R.string.sending_reply), "", NotifyManager.sPOST,
                            new Intent());
                }
                try {
                    // Sleep for 5 seconds
                    Thread.sleep(1);
                    NotifyManager.remove(mContext, NotifyManager.sPOST);
                } catch (InterruptedException e) {
                    // Toast.makeText(mContext, e.getMessage().toString(), Toast.LENGTH_LONG);
                    LogUtils.e(e.getMessage(), e);
                }

            }
        });

    }

    /**
     * 发帖成功
     */
    private void sendSuccess(final String rep) {
        final Intent intent = new Intent(mContext, MyPostActivity.class);
        HappyPetApplication.get().getUploaQueueImpl().removeQueue(this);
        // 如果是图片上传成功
        HappyPetApplication.get().getDBManager().deletePost(mPostInfos.postTime);
        HappyPetApplication.mHandler.post(new Runnable() {
            @Override
            public void run() {
                try {

                    JSONObject jo = new JSONObject(rep);

                    CommonUtil.showDialog2(mContext, jo.getString("jifentishi"));

                    CommonUtil.refurshWeiba(mContext);

                    // 判断是否需要分享
                    if (mPostInfos.isSendShare > 0) {
                        String url =
                                "http://bbs.chinapet.com/threadwap-" + jo.getString("tid")
                                        + ".html";
                        SharePopupWindow sharePopupWindow = new SharePopupWindow();
                        sharePopupWindow.setPostCome("threadpost");
                        sharePopupWindow.directSinaWeiboShare(mContext, String.format(
                                "#尾巴圈宠物#分享一篇好帖子：“%s”%s，@尾巴圈 ，我的养宠神器！下载地址》%s", mPostInfos.title,
                                url, mContext.getString(R.string.app_download_url)),
                                mPostInfos.successArray.first.size() == 0 ? null : new File(
                                        mPostInfos.successArray.first.get(0).first));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 区分是回复还是发帖
                if (TextUtils.isEmpty(mPostInfos.tid)) {
                    intent.putExtra(Constants.KEY_SKIP_TAB_INDEX, 0);
                    NotifyManager.showUploadPostNotify(mContext,
                            mContext.getString(R.string.send_post_success),
                            mContext.getString(R.string.send_post_success), "",
                            NotifyManager.sPOST, intent);
                } else {
                    intent.putExtra(Constants.KEY_SKIP_TAB_INDEX, 1);
                    NotifyManager.showUploadPostNotify(mContext,
                            mContext.getString(R.string.send_reply_success),
                            mContext.getString(R.string.send_reply_success), "",
                            NotifyManager.sPOST, intent);

                    Intent intent = new Intent();
                    intent.setAction("com.xindaoapp.com.huifu");
                    intent.putExtra(Constants.KEY_POST_TID, mPostInfos.tid);
                    // 要发送的内容
                    try {
                        intent.putExtra("finish", new String(rep));
                        // intent.putExtra("finish", new String(rep.getBytes("GBK"), "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 发送 一个无序广播
                    mContext.sendBroadcast(intent);
                    mPostInfos.tid = "";
                }
                NotifyManager.remove(mContext, NotifyManager.sPOST);
                iUploadProgress.success();
            }
        });
        // 删除掉数据中可能存储过的
        HappyPetApplication.get().getDBManager().deletePost(mPostInfos.postTime);
    }

    /**
     * 发送失败
     */
    private void sendFailed() {
        saveToDB();
        final Intent intent = new Intent(mContext, MyPostActivity.class);
        // 保存数据库
        HappyPetApplication.mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (TextUtils.isEmpty(mPostInfos.tid)) {
                    intent.putExtra(Constants.KEY_SKIP_TAB_INDEX, 0);
                    NotifyManager.showUploadPostNotify(mContext,
                            mContext.getString(R.string.send_post_failed),
                            mContext.getString(R.string.send_post_failed), "", NotifyManager.sPOST,
                            intent);
                } else {
                    intent.putExtra(Constants.KEY_SKIP_TAB_INDEX, 1);
                    NotifyManager.showUploadPostNotify(mContext,
                            mContext.getString(R.string.send_reply_failed),
                            mContext.getString(R.string.send_reply_failed), "",
                            NotifyManager.sPOST, intent);
                }
                NotifyManager.remove(mContext, NotifyManager.sPOST);

                String str = "";
                if (isFileError) {
                    str = "部分图片路径错误，请到草稿箱重新发送";
                }
                iUploadProgress.error(str);
                isFileError = false;
            }
        });
    }

    /**
     * 发送失败
     * 
     * @param errorMsg
     */
    private void sendFailed(final String errorMsg) {
        if (TextUtils.isEmpty(mPostInfos.tid))
            saveToDB();
        final Intent intent = new Intent(mContext, MyPostActivity.class);
        // 保存数据库
        HappyPetApplication.mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (TextUtils.isEmpty(mPostInfos.tid)) {// 发帖
                    intent.putExtra(Constants.KEY_SKIP_TAB_INDEX, 0);
                    NotifyManager.showUploadPostNotify(mContext, errorMsg, errorMsg, "",
                            NotifyManager.sPOST, intent);
                } else {
                    intent.putExtra(Constants.KEY_SKIP_TAB_INDEX, 1);
                    NotifyManager.showUploadPostNotify(mContext, errorMsg, errorMsg, "",
                            NotifyManager.sPOST, intent);
                }
                NotifyManager.remove(mContext, NotifyManager.sPOST);
                // iUploadProgress.error();
            }
        });
    }


    private String parseAidList(List<KeyValuePair<String, String>> list) {
        StringBuffer sb = new StringBuffer();
        if (infos == null) {
            for (int i = 0; i < list.size(); i++) {
                if (TextUtils.isEmpty(sb.toString())) {
                    sb.append(list.get(i).second);
                } else {
                    sb.append("," + list.get(i).second);
                }
            }
        } else {
            for (int i = 0; i < list.size(); i++) {
                // 判断是否为最终需要的图片，如果是，则添加进去
                for (KeyValuePair<String, Integer> pair : infos) {
                    if (pair.first.equals(list.get(i).first)) {
                        if (TextUtils.isEmpty(sb.toString())) {
                            sb.append(list.get(i).second);
                        } else {
                            sb.append("," + list.get(i).second);
                        }
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * 保存发帖状态
     */
    private void saveToDB() {
        if (null != infos) {
            // 对不需要的数据进行过滤删除
            for (int i = mPostInfos.sendingArray.size() - 1; i >= 0; i--) {
                for (KeyValuePair<String, Integer> pair : infos) {
                    if (pair.first.equals(mPostInfos.sendingArray.get(i))) {
                        mPostInfos.sendingArray.remove(i);
                        break;
                    }
                }
            }

            for (int i = mPostInfos.successArray.first.size() - 1; i >= 0; i--) {
                for (KeyValuePair<String, Integer> pair : infos) {
                    if (pair.first.equals(mPostInfos.successArray.first.get(i))) {
                        mPostInfos.successArray.first.remove(i);
                        break;
                    }
                }
            }
        }

        // 删除掉数据中可能存储过的
        HappyPetApplication.get().getDBManager().deletePost(mPostInfos.postTime);
        HappyPetApplication.get().getDBManager().insertPost(mPostInfos);
    }

    @Override
    public PostInfo3 getPostInfo() {
        return mPostInfos;
    }

    @Override
    public boolean isRunning() {
        return isPosting;
    }

    @Override
    public void setFid(String fid, String tags, String shaituid) {
        try {
            JSONObject jo = new JSONObject();
            jo.put("fid", fid);
            jo.put("tagidlist", tags);
            jo.put("shaituid", shaituid);
            mPostInfos.fid = jo.toString();
        } catch (Exception e) {
        }
    }

    @Override
    public void setFid(String fid, String tags, String shaituid, String mapx, String mapy,
            String location, String locationname, String city) {
        try {
            JSONObject jo = new JSONObject();
            jo.put("fid", fid);
            jo.put("tagidlist", tags);
            jo.put("shaituid", shaituid);
            jo.put("mapx", mapx);
            jo.put("mapy", mapy);
            jo.put("location", location);
            jo.put("locationname", locationname);
            jo.put("city", city);
            mPostInfos.fid = jo.toString();
        } catch (Exception e) {
        }
    }
}
